/**
 * @description vite自定义插件 - 捕获全局报错 + 上传错误日志
 * @author 叶花弈
 * @lastModify 2024-08-07
 */

export default (options = { system: null, baseUrl: null }) => {
  const { system, baseUrl } = options;
  if (!system || !baseUrl) throw new Error("[异常捕获]: 请检查入参");
  const script = `
    console.log("%c[异常捕获]: 初始化成功-${system}", "color: green");
    // 上报错误日志
    const sendErrorLog = (message) => {
      const page = encodeURIComponent(window.location.href);
      const token = localStorage.getItem("token");
      const error = encodeURIComponent(message);
      const url = "${baseUrl}/sendErrorLog?system=${system}" + "&page=" + page + "&token=" + token + "&error=" + error;
      navigator.sendBeacon(url)
    }
    // 捕获异常
    window.addEventListener("error", (event) => {
      // 不存在error
      if (!event.error) {
        sendErrorLog(event.message);
      }
      // 存在error.stack栈信息
      else if (event.error?.stack) {
        sendErrorLog(event.error.stack);
      }
      // 不存在error.stack栈信息
      else {
        const errorJson = JSON.stringify(event.error, Object.getOwnPropertyNames(event.error), 2);
        sendErrorLog(errorJson);
      }
    });
    window.addEventListener("unhandledrejection", (event) => {
      event.reason?.stack && sendErrorLog(event.reason.stack);
    });
  `;
  return {
    name: "vite-plugin-catchError",
    transform(code, id) {
      // 往main.js里面注入JS代码
      if (id.endsWith("main.js")) {
        return `${code}\n${script}`;
      }
    },
  };
};
